[fix][ml] Prevent terminated managed ledger from transitioning back to writable state#25795
[fix][ml] Prevent terminated managed ledger from transitioning back to writable state#25795void-ptr974 wants to merge 2 commits into
Conversation
When terminate() races with ledger rollover, a delayed rollover completion can overwrite the Terminated state and move the ManagedLedger back to LedgerOpened. The concrete race is: an add fills the current ledger and starts creating the next ledger, terminate() marks the ManagedLedger as Terminated, then the delayed createComplete/updateLedgersIdsComplete callback resumes the old rollover path and reopens the ledger for writes. This commit makes the rollover completion path respect Terminated as a final write state. Late createComplete callbacks close the newly created ledger handle and fail queued adds with ManagedLedgerTerminatedException. Late updateLedgersIdsComplete callbacks return without setting LedgerOpened, and the close-ledger path no longer creates a replacement ledger after termination.
| State state = STATE_UPDATER.get(ManagedLedgerImpl.this); | ||
| if (state == State.Closed || state.isFenced()) { | ||
| log.debug().log("skip ledger update after create complete ledger is closed or fenced"); | ||
| if (state == State.Closed || state == State.Terminated || state.isFenced()) { |
There was a problem hiding this comment.
I think this branch still leaves one terminate-vs-rollover race unresolved. By the time this callback reaches operationComplete, updateLedgersListAfterRollover has already successfully written metadata that includes newLedger. If terminate() is concurrently writing the terminated metadata, the two store.asyncUpdateLedgerIds(...) calls can still race because asyncTerminate is not serialized with this metadataMutex path.
There are two problematic outcomes: if the rollover metadata update wins first, this branch only closes lh and relies on a later terminate metadata update to remove the new ledger from metadata, but the unused BookKeeper ledger is not deleted; if terminate wins the metadata version race first, this rollover callback can go through operationFailed(BadVersionException) and call handleBadVersion, fencing a ledger that should remain terminated. The TODO here is therefore part of the correctness fix, not just cleanup.
Can we make the in-flight rollover metadata update terminal-state aware as well, e.g. serialize terminate with the same metadata update path, or handle state == Terminated in both the success and BadVersion failure callbacks as a stale rollover completion, while ensuring the unused ledger is removed from metadata and deleted if it was already written?
There was a problem hiding this comment.
Thanks for the detailed explanation. I’ve also identified this remaining
terminate-vs-rollover metadata race.
The ManagedLedger code path is quite complex, so I think it would be clearer
and safer to split the related fixes into smaller PRs instead of carrying all
of them in this one. This PR focuses on the terminated-state transition and
pending-add handling.
After this PR is merged, I’ll submit a follow-up PR to address the metadata
update race, including the stale rollover success path, the BadVersion path,
and cleanup of any unused ledger that may have been written to metadata.
There was a problem hiding this comment.
Unresolving this comment since there's very useful observations and analysis so far and it's useful to keep the thread visible until we agree on how to address the problems in short term and long term.
I agree that the current ManagedLedgerImpl code path is quite complex. It's hard to reason about the correctness since it's a mixture of locks, synchronization and different executors.
Just wondering if terminate should be implemented in a way where the state is set to "Terminating" which would be used to prevent any new operations starting, but existing inflight operations would first be completed before the ManagedLedgerImpl could be transitioned into "Terminated" state? The transitioning from Terminating to Terminated would be handled after the metadata update has been successfully completed. If there's a crash in the metadata update, the ledger will continue to be operational. The client requesting the termination can retry if it doesn't receive a successful response to the termination request.
WDYT?
There was a problem hiding this comment.
Thanks for the detailed review. I agree the terminate-vs-rollover metadata race is important.
For this PR, I would like to keep the scope focused on the immediate terminated-state and pending-add behavior: once termination has taken effect, late callbacks should not move the managed ledger back to a writable state, and pending add callbacks should complete consistently.
The metadata race is a different path and the fix is more involved. A focused follow-up PR would need to handle the terminate metadata update together with the metadataMutex-serialized metadata update path, including:
- stale rollover metadata success after termination, where we may need metadata cleanup and unused BookKeeper ledger cleanup;
- stale rollover metadata failure after termination wins, where
BadVersionExceptionshould not fence a ledger that is already terminating/terminated.
Mixing that into this PR would make the review much harder because it combines state/callback behavior with metadata serialization and ledger cleanup. My preference is to keep this PR focused, then send a separate PR for the metadataMutex / stale rollover metadata path.
I agree that a separate Terminating state would be a cleaner long-term model.
The distinction I have in mind is:
Terminating: termination has started on this broker. New writes and new rollovers should be rejected, late callbacks should not move the ledger back to writable, and existing in-flight adds should either drain or fail deterministically.Terminated: the terminate metadata update has succeeded andterminatedPositionis durable.
With this model, Terminating does not need to be the durable state. If the broker crashes before the metadata update succeeds, recovery can treat the ledger as non-terminated and the caller can retry termination. If the metadata update succeeds, recovery observes terminatedPosition and restores Terminated.
This would make the state machine easier to reason about, but it still needs a clear design for how it interacts with rollover callbacks, pending add entries, metadata updates, and BadVersionException handling. It also would not replace the need to fix the metadataMutex race; it mainly gives us a clearer lifecycle boundary so those cases can be handled consistently.
I think this is worth doing as a follow-up design/change.
There was a problem hiding this comment.
For this PR, I would like to keep the scope focused on the immediate terminated-state and pending-add behavior: once termination has taken effect, late callbacks should not move the managed ledger back to a writable state, and pending add callbacks should complete consistently.
It just feels that this approach isn't correct. The problem itself is real.
I think this is worth doing as a follow-up design/change.
Yes, it most likely makes sense to start with the analysis and design. In Pulsar, it's most natural to document the problem, analysis and design into a PIP before implementation (prototypes and experimentation are obviously recommended and necessary when coming up with the design).
There was a problem hiding this comment.
Thanks, that makes sense to me.
I’ll take a deeper look at the overall ManagedLedger termination flow and how these issues should be handled together, including the state transition model, the metadata update/locking path, and stale rollover callbacks.
After that, I’ll try to prepare a proper PIP or design proposal so we can discuss the problem, analysis, and proposed approach more clearly with the community.
| assertTrue(createRequested.await(5, TimeUnit.SECONDS)); | ||
| assertEquals(ledger.getState(), ManagedLedgerImpl.State.CreatingLedger); | ||
|
|
||
| CountDownLatch addFailed = new CountDownLatch(1); |
| // TODO: if this path is hit after the new ledger was already written into metadata, | ||
| // delete the unused ledger together with removing it from the metadata. |
Related issue
Fixes #25858
Motivation
ManagedLedger.terminate()seals the managed ledger at the current BookKeeper committed boundary. After termination, no new entries should be accepted, and the managed ledger must notbecome writable again.
The key invariant is:
terminate()does not wait for every submitted add to succeed. It closes the current BookKeeper ledger and uses the ledger's final LAC as theterminatedPosition.Therefore:
terminate();ManagedLedgerTerminatedException;There is a race between
terminate()and ledger rollover:ClosingLedger/CreatingLedger.terminate()runs before the rollover create/switch callback finishes and marks the managed ledger asTerminated.createComplete()orupdateLedgersIdsComplete()callback resumes the old rollover flow.LedgerOpened, making a terminated managed ledger writable again.This breaks the terminate semantics. It can also leave pending writes handled as normal rollover writes instead of terminated writes, or leave in-flight add callbacks hanging when
BookKeeper close drains writes that were not included in the final LAC.
Modifications
This change keeps
Terminatedas the final write state afterterminate()takes ownership.The implementation follows one invariant:
To keep that invariant, this PR handles each race path explicitly:
Queued adds that have not been sent to BookKeeper
terminate()takes ownership, these adds are failed withManagedLedgerTerminatedException.In-flight adds already sent to BookKeeper
terminatedPosition.Failed add callbacks after terminate
failAddIfTerminated()for failed add callbacks that arrive after terminate has taken ownership.Terminatedstate,ledgerClosed()returns without replaying or failing the add, leaving the client callbackhanging.
Late ledger create callbacks
createComplete()now completes the ledger-create future before terminal-state checks.Late ledger switch callbacks
updateLedgersIdsComplete()now returns when the managed ledger is alreadyTerminated.LedgerOpened.Replacement ledger creation after close
Terminated.This does not change the public API, protocol, schema, or metric names. It only fixes the behavior of existing state transitions and balances the existing pending ledger-create metric in
the late-callback path.
Verifying this change
This change added tests and can be verified as follows:
terminateDuringLedgerSwitchKeepsTerminatedStateterminate().Terminated.ManagedLedgerTerminatedException.terminatePositionIncludesAddAlreadyAckedByBookKeeperterminate()returns aterminatedPositionthat includes the acknowledged add.terminateFailsInflightAddDrainedByLedgerCloseManagedLedgerTerminatedException.ledgerSwitchCompletionDoesNotReopenTerminatedLedgerTerminatedback toLedgerOpened.Local verification:
./gradlew :managed-ledger:test --tests org.apache.bookkeeper.mledger.impl.ManagedLedgerTerminationTest
./gradlew :managed-ledger:checkstyleMain :managed-ledger:checkstyleTest
Does this pull request potentially affect one of the following parts: